﻿#include "logmodel.h"

#include <algorithm>

LogModel::LogModel(QObject* parent)
    : QAbstractTableModel(parent)
{}

int LogModel::rowCount(const QModelIndex&) const
{
    return m_filteredEntries.size();
}

int LogModel::columnCount(const QModelIndex&) const
{
    return ColumnCount;
}

QVariant LogModel::data(const QModelIndex& index, int role) const
{
    if (!index.isValid())
        return QVariant();

    const auto& entry = m_filteredEntries[index.row()];
    switch (index.column()) {
    case Timestamp: return role == Qt::DisplayRole ? entry.timestamp : QVariant();
    case ThreadID:  return role == Qt::DisplayRole ? entry.threadId  : QVariant();
    case FileName:     return role == Qt::DisplayRole ? entry.fileName     : QVariant();
    case LineNumber:     return role == Qt::DisplayRole ? entry.lineNumber     : QVariant();
    case Level:     return role == Qt::DisplayRole ? entry.level     : QVariant();
    case Content:   return role == Qt::DisplayRole ? entry.content   : QVariant();
    default:        return QVariant();
    }
}

QVariant LogModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case Timestamp: return tr("时间");
        case ThreadID:  return tr("线程");
        case FileName:  return tr("文件名");
        case LineNumber:  return tr("行数");
        case Level:     return tr("等级");
        case Content:   return tr("内容");
        }
    }
    return QVariant();
}
#include <qdebug.h>
#include <qthread.h>
void LogModel::addEntries(const QVector<LogEntry>& entries)
{
    if(entries.size() <= 1)
    {
        return;
    }
    qDebug()<<"begin threadid :"<<QThread::currentThreadId()<<" "<<m_allEntries.size()<<" "<<entries.size();
    beginInsertRows(QModelIndex(), m_allEntries.size(), m_allEntries.size() + entries.size() - 1);
    qDebug()<<"begin1 threadid  :"<<QThread::currentThreadId();
    m_allEntries.append(entries);
    qDebug()<<"begin2 threadid :"<<QThread::currentThreadId();
    endInsertRows();
    qDebug()<<"begin3 threadid :"<<QThread::currentThreadId();

    // 更新过滤结果
    setFilter(m_threadFilter, m_levelFilter, m_keywordFilter);
    qDebug()<<"begin4 threadid :"<<QThread::currentThreadId();
}

void LogModel::clear()
{
    beginResetModel();
    m_allEntries.clear();
    m_filteredEntries.clear();
    endResetModel();
}

void LogModel::setFilter(const QString& thread, const QString& level, const QString& keyword)
{
    m_threadFilter = thread;
    m_levelFilter = level;
    m_keywordFilter = keyword;

    m_filteredEntries.clear();
    std::copy_if(m_allEntries.begin(), m_allEntries.end(),
                 std::back_inserter(m_filteredEntries),
                 [&](const LogEntry& e){
                     return e.match(thread, level, keyword);
                 });

    emit layoutChanged();
}
